import webapp2
import os
from google.appengine.ext.webapp import util
import urllib2 , simplejson
from operator import itemgetter
from webapp2_extras import jinja2

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        # Returns a Jinja2 renderer cached in the app registry.
        return jinja2.get_jinja2(app=self.app)

    def render_response(self, _template, **context):
        # Renders a template and writes the result to the response.
        rv = self.jinja2.render_template(_template, **context)
        self.response.write(rv)

        
class HelloWebapp2(BaseHandler):
    def get(self):
        u = urllib2.urlopen('http://www.stockbangladesh.com/resources/getpricelist')
        result = u.read()
        result = result[1:len(result)-1]
        #result = json.read(result)
        result = "[" + result + "]"
        result = simplejson.loads(result)
        #self.response.write(result)
        context = {"result": sorted(result[0]['results'], key=itemgetter('code'))}
        path = os.path.join(os.path.dirname(__file__), '../views' ,'index.html')
        self.render_response('index.html', **context)
        
def main():
    app = webapp2.WSGIApplication([
        ('/', HelloWebapp2),
    ], debug=True)
    util.run_wsgi_app(app)


if __name__ == '__main__':
	main()